package com.dengpp.pdform.holder;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dengpp.pdform.R;
import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.base.BaseAttributeViewHolder;
import com.dengpp.pdform.config.AttributeConfig;
import android.widget.EditText;


public class TextViewHolder extends BaseAttributeViewHolder {
    private EditText editText;
    private TextView tvValue;
    private TextView tvTitle;
    private TextWatcher textWatcher;
    private AttributeConfig currentAttribute;

    public TextViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tv_title);
        editText = itemView.findViewById(R.id.edit_text);
        tvValue = itemView.findViewById(R.id.tv_value);
    }

    @Override
    public void bind(AttributeConfig attribute, boolean isEditMode, AttributeAdapter.OnAttributeChangeListener listener) {
        // 保存当前绑定的属性
        this.currentAttribute = attribute;

        // 移除旧的 TextWatcher
        if (textWatcher != null) {
            editText.removeTextChangedListener(textWatcher);
        }

//        if(attribute.isHide()){
//            tvTitle.setText(attribute.getTitle());
//            editText.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
//            tvValue.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
//
//            tvTitle.setVisibility(View.GONE);
//            editText.setVisibility(View.GONE);
//            tvValue.setVisibility(View.GONE);
//            return;
//        }

        // 使用带星号的标题
        tvTitle.setText(getTitleWithRequiredStar(attribute.getTitle(), attribute.isRequired()));

        if (isEditMode && attribute.isEditable()) {
            editText.setVisibility(View.VISIBLE);
            tvValue.setVisibility(View.GONE);

            // 先设置文本，再添加监听器，避免触发不必要的回调
            editText.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
            if (attribute.getHint() != null) {
                editText.setHint(attribute.getHint());
            }

            // 设置最大长度
            if (attribute.getMaxLength() > 0) {
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(attribute.getMaxLength())});
            }

            // 创建新的 TextWatcher
            textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}

                @Override
                public void afterTextChanged(Editable s) {
                    String input = s.toString();

                    // 确保当前属性仍然匹配
                    if (currentAttribute != attribute) {
                        return;
                    }

                    // 自定义输入验证
                    String validationRule = attribute.getValidationRule();
                    if (validationRule != null && !isValidInput(input, validationRule)) {
                        editText.setError(attribute.getValidationMessage());
                    } else {
                        editText.setError(null);
                    }

                    if (listener != null) {
                        listener.onAttributeChanged(attribute.getKey(), input);
                    }
                }
            };

            editText.addTextChangedListener(textWatcher);
        } else {
            editText.setVisibility(View.GONE);
            tvValue.setVisibility(View.VISIBLE);
            tvValue.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
        }
    }

    /**
     * 在 ViewHolder 被回收时清理资源
     */
    @Override
    public void onViewRecycled() {
        super.onViewRecycled();
        if (textWatcher != null) {
            editText.removeTextChangedListener(textWatcher);
            textWatcher = null;
        }
        currentAttribute = null;
    }

    /**
     * 验证输入是否符合规则
     */
    private boolean isValidInput(String input, String validationRule) {
        if (input == null || input.isEmpty()) {
            return true; // 空值在必填验证中处理
        }

        switch (validationRule) {
            case "phone":
                return input.matches("\\d{7,15}");
            case "email":
                return input.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
            case "id_card":
                return input.matches("\\d{17}[\\dXx]");
            case "chinese":
                return input.matches("[\\u4e00-\\u9fa5]+");
            case "english":
                return input.matches("[a-zA-Z]+");
            case "no_special_chars":
                return input.matches("[\\w\\u4e00-\\u9fa5]+");
            default:
                // 如果是正则表达式，直接使用
                return input.matches(validationRule);
        }
    }
}
